package com.chs.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.chs.util.ResultUtil;
import com.chs.util.TokenUtil;

/**
 * 验证token是否失效 springboot需要加@Component
 */
@Component
@WebFilter(filterName = "TokenFilter", urlPatterns = "/*")
@Order(0)
public class TokenFilter implements Filter {

	private static List<String> us = new ArrayList<>();
	static {
		us.add("/admin/login");
		
		us.add("/login");
		us.add("/get-code");
		us.add("/register");
		us.add("/pwd-check-code");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		req.setCharacterEncoding("utf-8");
		res.setCharacterEncoding("utf-8");

		String reqURI = req.getRequestURI();
		System.err.println("uri："+reqURI);
		if (us.contains(reqURI)) {
			chain.doFilter(req, res);
		} else {
			// 是否失效
			String token = req.getHeader("Authorization");

			if (token != null && !"".equals(token)) {
				boolean result = TokenUtil.verify(token);
				if (result) {
					chain.doFilter(req, res);
				} else {
					responseMessage(res, res.getWriter(), ResultUtil.ok(-2, "身份过期，请重新登录！", null));
				}
			} else {
				responseMessage(res, res.getWriter(), ResultUtil.ok(-2, "身份过期，请重新登录！", null));
			}
		}

		return;
	}

	@Override
	public void destroy() {
	}

	/**
	 * 返回信息给客户端
	 *
	 * @param response
	 * @param out
	 * @param object
	 */
	private void responseMessage(HttpServletResponse response, PrintWriter out, Object object) {
		response.setContentType("application/json; charset=utf-8");
		String json = JSON.toJSONString(object);
		out.print(json);
		out.flush();
		out.close();
	}
}
